package com.byx.imserverutil;

import com.byx.imserverutil.factory.ImServiceFactory;
import com.byx.imserverutil.listener.OnMessageReceivedListener;
import com.byx.imserverutil.service.ImService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * ImServerUtilRun
 * 启动类
 * @author Superb
 * @date 2021/2/9 15:41
 */
public class ImServerUtilRun {
    private static final Logger logger=LoggerFactory.getLogger(ImServerUtilRun.class);

    private ImService imService;

    public static ImServerUtilRun getInstance(){
        return Holder.INSTANCE;
    }

    private static final class Holder{
        private static final ImServerUtilRun INSTANCE = new ImServerUtilRun();
    }

    private boolean init(int port, OnMessageReceivedListener onMessageReceivedListener){
        imService=ImServiceFactory.getImService();
        if(null == imService){
            logger.warn("ImServerUtilRun初始化失败：imService 为 null");
            return false;
        }
        boolean initialized=imService.initialize(port,onMessageReceivedListener);
        if(!initialized){
            logger.warn("ImServerUtilRun初始化失败：请查看 " + imService.getClass().getSimpleName() + " 相关的日志");
            return false;
        }
        logger.warn("ImServerUtilRun初始化完成\nimService = " + imService.getClass().getSimpleName() + "\nport = " + port);
        return true;
    }

    private void start(){
        if(null == imService){
            logger.warn("ImService启动失败");
            return;
        }
        imService.start();
    }

    public void run(int port, OnMessageReceivedListener onMessageReceivedListener){
        boolean initialized = init(port,onMessageReceivedListener);
        if(initialized){
            start();
        }
    }

    public void release(){
        if (null != imService){
            imService.release();
        }
    }
}
